package com.forlove.app.qselect.answer.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.forlove.app.common.base.mvp.presenter.IBasePresenter;
import com.forlove.app.common.utils.LogUtil;
import com.forlove.app.common.utils.NetworkUtils;
import com.forlove.app.common.utils.StringUtils;
import com.forlove.app.manager.FriendManager;
import com.forlove.app.qselect.friend.entity.MineFriendEntity;
import com.forlove.app.qselect.login.entity.ContactsInfoEntity;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by yjl on 2017/12/5.
 */

public abstract class BaseCandidateFragment extends Fragment implements CandidateListener {
    public static final int position_choice_friend = 0;
    public static final int position_set_candidate = 1;
    protected static List<MineFriendEntity> mineFriendEntities = new ArrayList<>();
    protected static List<MineFriendEntity> selectFriend = new ArrayList<>();//选择了的候选人好友
    protected static List<MineFriendEntity> queryFriend = new ArrayList<>();//搜索结果的firend
    protected static Handler friendHandler;
    protected static HandlerThread handlerThread;
    protected static Handler dataHandler;
    private LayoutInflater mInflater;
    private View mView;
    protected IBasePresenter basePresenter;
    protected SelectFriendListener selectFriendListener;

    protected abstract void initViews();

    protected abstract int getLayoutId();

    protected <T extends View> T findViewById(int id) {
        return mView.findViewById(id);
    }

    protected void runOnUiThread(Runnable action) {
        getActivity().runOnUiThread(action);
    }

    protected LayoutInflater getInflater() {
        return mInflater;
    }

    public void setPresenter(IBasePresenter presenter) {
        this.basePresenter = presenter;
    }

    public void setSelectFriendListener(SelectFriendListener selectFriendListener) {
        this.selectFriendListener = selectFriendListener;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mInflater = inflater;
        mView = mInflater.inflate(getLayoutId(), container, false);
//        if (friendHandler == null) {
            friendHandler = new Handler(Looper.getMainLooper(), new Handler.Callback() {
                @Override
                public boolean handleMessage(Message msg) {
                    if (msg.what == 10086) {
                        LogUtil.e("yjl", getClass().getSimpleName() + " BaseCandidateFragment position");
                        updateView();
                    }
                    return false;
                }
            });
//        }
        initViews();
        return mView;
    }


    /**
     * 设置好友数据
     *
     * @param recommendFriend      上一批推荐好友
     * @param qyqFriends           圈一圈好友
     * @param contactsInfoEntities 通讯录好友
     */
    public static synchronized void setFriendsData(final List<MineFriendEntity> recommendFriend,
                                                   final List<MineFriendEntity> qyqFriends,
                                                   final List<ContactsInfoEntity> contactsInfoEntities) {
        if (handlerThread == null) {
            handlerThread = new HandlerThread("loadFriend");
            handlerThread.start();
        }
        if (dataHandler == null) {
            dataHandler = new Handler(handlerThread.getLooper());
        }
        dataHandler.post(new Runnable() {
            @Override
            public void run() {
                List<MineFriendEntity> list = FriendManager.getSubjectCandidate(recommendFriend, qyqFriends, contactsInfoEntities, -1);
                synchronized (list) {
                    if (list != null && list.size() > 0) {
                        mineFriendEntities.clear();
                        mineFriendEntities.addAll(FriendManager.sortRegisterFriend(list));
                    }
                    selectFriend.clear();
                    selectFriend.addAll(recommendFriend);
                    if (friendHandler != null) {
                        friendHandler.sendEmptyMessage(10086);
                    }
                }
            }

        });

    }

    /**
     * 调起activity。
     *
     * @param intent  Intent
     * @param isClose 是否关闭当前activity。
     */
    public void startActivity(Intent intent, boolean isClose) {
        super.startActivityForResult(intent, 1);
        if (isClose && getActivity() != null) {
            getActivity().finish();
        }
    }


    protected boolean isNetworkAvailable() {
        if (NetworkUtils.instance(getActivity()).isNetworkAvailable()) {
            return true;
        } else {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getContext(), "请检查网络！", Toast.LENGTH_SHORT).show();
                }
            });
            return false;
        }
    }

    public void clearData() {
        if (handlerThread != null) {
            handlerThread.quitSafely();
            handlerThread = null;
        }
        if (dataHandler != null) {
            dataHandler.removeCallbacksAndMessages(null);
            dataHandler = null;
        }
        if (friendHandler != null) {
            friendHandler.removeCallbacksAndMessages(null);
            friendHandler = null;
        }

        mineFriendEntities.clear();
        selectFriend.clear();
        queryFriend.clear();
        basePresenter = null;
        selectFriendListener = null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    public interface SelectFriendListener {
        void selectedFirend(List<MineFriendEntity> mineFriendEntities, int position);

        void closeDialog();
    }

    protected void updateView() {

    }

    /**
     * 搜索好友
     *
     * @param queryStr
     * @return
     */
    protected List<MineFriendEntity> getLocalSearchFriend(String queryStr) {

        List<MineFriendEntity> local = new ArrayList<>();
        for (MineFriendEntity friendEntity : mineFriendEntities) {
            if (StringUtils.isNotEmpty(queryStr) &&
                    ((StringUtils.isNotEmpty(friendEntity.getAvaliableName()) && friendEntity.getAvaliableName().contains(queryStr))
                            || (StringUtils.isNotEmpty(friendEntity.mobile) && friendEntity.mobile.contains(queryStr))
                            || (StringUtils.isNotEmpty(friendEntity.contactsNumber) && friendEntity.contactsNumber.contains(queryStr))
                            || (StringUtils.isNotEmpty(friendEntity.contactsName) && friendEntity.contactsName.contains(queryStr))
                    )) {
                local.add(friendEntity);
            }
        }
        return local;
    }
}
